# application/services/system/dict.py
from application.mapper.system.dict_data import DictDataMapper
from typing import Dict, Any, List
from application.models.system.dict_data import SysDictData
from application.utils.res import models_to_dicts_camel, to_snake_case


class DictDataService:
    """字典数据服务层"""

    @staticmethod
    def get_dict_data_list(
        page_num: int, page_size: int, conditions: Dict[str, Any] = None
    ) -> Dict[str, Any]:
        """
        分页获取字典数据列表
        :param page_num: 页码
        :param page_size: 每页数量
        :param conditions: 查询条件
        :return: 字典数据分页结果
        """
        dict_data_list, total = DictDataMapper.get_dict_data_list(
            page_num, page_size, conditions
        )

        result_list = models_to_dicts_camel(dict_data_list)

        return result_list, total

    @staticmethod
    def get_dict_data_by_type(dict_type: str) -> Dict[str, Any]:
        """
        根据字典类型获取字典数据列表
        :param dict_type: 字典类型
        :return: 字典数据列表
        """
        dict_data_list = DictDataMapper.get_dict_data_by_type(dict_type)

        result_list = models_to_dicts_camel(dict_data_list)

        return result_list
    
    @staticmethod
    def create_dict_data(data: Dict[str, Any]) -> Dict[str, Any]:
        """
        创建字典数据
        :param product_model_data: 字典数据数据
        :return: 创建后的字典数据数据
        """
        # 创建字典数据对象
        dict_data = SysDictData()

        for key, value in data.items():

            snake_key = to_snake_case(key)
            if hasattr(dict_data, snake_key):
                setattr(dict_data, snake_key, value)
        
        created_model = DictDataMapper.create_dict_data(dict_data)
        return models_to_dicts_camel([created_model])[0]


    @staticmethod
    def update_dict_data(dict_code: int, dict_data_data: Dict[str, Any]) -> Dict[str, Any]:
        """
        更新字典数据
        :param dict_code: 字典数据ID
        :param product_model_data: 字典数据数据
        :return: 更新后的字典数据数据
        """
        product_model = DictDataMapper.get_dict_data_by_code(dict_code)
        
        if not product_model:
            return None
            
        # 更新字典数据对象
        for key, value in dict_data_data.items():
            snake_key = to_snake_case(key)
            if hasattr(product_model, snake_key):
                setattr(product_model, snake_key, value)
        
        updated_model = DictDataMapper.update_dict_data(product_model)
        return models_to_dicts_camel([updated_model])[0]


    
    @staticmethod
    def batch_delete_dict_data(dict_code: list) -> bool:
        """
        批量删除字典
        :param dict_code: 字典ID列表
        :return: 删除的记录数
        """
        deleted_count = DictDataMapper.batch_delete_dict_data(dict_code)
        return deleted_count